require("./sass/style.scss");
require("../../sass/dropzone.css");

const _ = require("lodash");
const clubInfoTmpl = require("./tmpl/build/template");
const NProgress = require("nprogress");

import getPageHeader from "../../components/page_header/header.js";
import CollapseList from "../../components/collapse_list/index.js";
import {getClubInfo, putHonor, delHonor, updateClubInfo, delClubImage} from "../dao.js";
import Validator from "../../components/formValidator/validator.js";
import ImagePlugin from "../../components/imagePlugin/image.js";
import waitMe from "../../components/waitMe/index.js";
import confirmModal from "../../components/confirmModal/modal.js";

class ClubInfo {
    constructor (dom, club_id){
        this.container = dom;
        this.club_id = club_id;
        this.init();
        this.data = null;
        this.images = {};
        this.imageCollapsedList = null;
        this.honorCollapsedList = null;
    }

    initThirdComponenets () {
        getPageHeader(this.club_id, true).render("[data-page-header]");
        this.initHonorList(this.data.honors);
        this.initImageList(this.data.images);
    }

    /**
     * 初始化 Honor List
     */
    initHonorList (honors) {
        var that = this;
        var config = {
            data: ((honors)=>{
                var result = [];
                _.forEach(honors, function(h){
                    result.push({
                        title: h.year + " " + h.title,
                        body: clubInfoTmpl("honor", h),
                        id: "club-honor-" + h.id
                    });
                });
                result.push({
                    title: "添加荣誉",
                    body: clubInfoTmpl("honor", {
                        is_submit: true
                    }),
                    id: "new-club-honor",
                    delete: false
                });
                return result;
            })(honors),
            container: this.container + " [data-club-honors]",
            eventHandler: {
                click: function(){
                    var args = Array.prototype.slice.apply(arguments);
                    var collapseList = args.shift();
                    var event = args.shift();
                    var target = event.target;
                    if($(target).data("action") === "save-honor"){
                        let parent = $(target).parents(".panel-body").parent();
                        let year = $(parent).find("[data-honor-year]").val();
                        let title = $(parent).find("[data-honor-title]").val();
                        if(parent.attr("id") === "new-club-honor"){
                            // add new honor
                            if (that.validateHonor("#new-club-honor")){
                                waitMe.show();
                                putHonor(that.club_id, year, title)
                                .then((data)=>{
                                    collapseList.unshift({
                                        title: year + " " + title,
                                        body: clubInfoTmpl("honor", {
                                            year: year,
                                            title: title,
                                            id: data.id
                                        }),
                                        id: "club-honor-" + data.id
                                    });

                                    $(parent).find("[data-honor-year]").val("");
                                    $(parent).find("[data-honor-title]").val("");
                                    collapseList.hide("new-club-honor");
                                    
                                    waitMe.hide();
                                }).catch((err)=>{
                                    console.error(err);
                                    waitMe.hide();
                                });
                            }
                        }
                    }
                },
                delete: function(){
                    var args = Array.prototype.slice.apply(arguments);
                    confirmModal.show(function(){
                        waitMe.show();
                        var collapseList = args.shift();
                        var event = args.shift();
                        var target = event.target;
                        var honor_id = $(target).find("[data-club-honor-id]").data("club-honor-id");
                        delHonor(that.club_id, honor_id).then((data)=>{
                            collapseList.delete("club-honor-" + honor_id);
                            waitMe.hide();
                        }).catch((err)=>{
                            console.error(err);
                            waitMe.hide();
                        });
                    });
                }
            },
            collapseId: "club-honor"
        };
        this.honorCollapsedList = new CollapseList(config);
    }

    /**
     * 初始化 Image List
     */
    initImageList (images) {
        var that = this;
        var config = {
            data: ((imgs)=>{
                var result = [];
                _.forEach(imgs, (i)=>{
                    result.push({
                        title: i.description,
                        body: clubInfoTmpl("image", i),
                        id: "club-image-" + i.id
                    });
                    this.images["club-image-" + i.id] = {
                        src: i.url,
                        is_upload: false
                    };
                });
                result.push({
                    title: "添加图片",
                    body: clubInfoTmpl("image", {
                        is_submit: true
                    }),
                    id: "new-club-image",
                    delete: false
                });
                this.images["new-club-image"] = {
                    src: "",
                    url: "web/club/putClubImage/",
                    is_upload: true,
                    eventHandler: {
                        upload: function(formData){
                            if(!that.validateClubImage("#new-club-image")){
                                return false;
                            }
                            waitMe.show();
                            var description = $("#new-club-image").find("[data-club-img-description]").val();
                            formData.append("description", description);
                            formData.append("club_id", that.club_id);
                            return true;
                        },
                        success: function(res){
                            that.imageCollapsedList.unshift({
                                title: res.data.description,
                                body: clubInfoTmpl("image", {
                                    description: res.data.description,
                                    id: res.data.id
                                }),
                                id: "club-image-" + res.data.id
                            });
                            that.images["club-image-" + res.data.id] = {
                                imgObj: new ImagePlugin({
                                    container: "#club-image-" + res.data.id + " [data-club-image]",
                                    height: "",
                                    width: "100%",
                                    src: res.data.url,
                                    is_upload: false,
                                })
                            };
                            
                            // 清空 image
                            that.images["new-club-image"].imgObj.clearSrc();
                            $("#new-club-image").find("[data-club-img-description]").val("");

                            that.imageCollapsedList.hide("new-club-image");
                            waitMe.hide();
                        },
                        fail: function(err){
                            console.error(err);
                            waitMe.hide();
                        }
                    }
                };
                return result;
            })(images),
            container: this.container + " [data-club-images]",
            collapseId: "club-image",
            eventHandler: {
                click: function(){
                    var args = Array.prototype.slice.apply(arguments);
                    var collapseList = args.shift();
                    var event = args.shift();
                    var target = event.target;
                    if($(target).data("action") === "save-club-image"){
                        that.images["new-club-image"].imgObj.upload();
                    }
                },
                delete: function(){

                    var args = Array.prototype.slice.apply(arguments);

                    confirmModal.show(function(){
                        waitMe.show();
                        var collapseList = args.shift();
                        var event = args.shift();
                        var target = event.target;
                        var image_id = $(target).find("[data-club-image-id]").data("club-image-id");
                        delClubImage(that.club_id, image_id).then(function(){
                            collapseList.delete("club-image-" + image_id);
                            delete that.images["club-image-" + image_id];
                            waitMe.hide();
                        }).catch(function(err){
                            console.error(err);
                            waitMe.show();
                        });
                    });

                }
            }
        };
        this.imageCollapsedList = new CollapseList(config);
        // render img
        _.forOwn(this.images, (image, key)=>{
            this.images[key].imgObj = new ImagePlugin({
                container: "#" + key + " [data-club-image]",
                height: "",
                width: "100%",
                src: image.src,
                is_upload: image.is_upload,
                url: image.url,
                eventHandler: image.eventHandler
            });
        });
    }

    init () {
        NProgress.start();
        getClubInfo(this.club_id).then((res)=>{
            this.data = res.data.clubInfo;
            if(this.data){
                this.render();
                this.bindEvent();
            }else{
                // show error hint
                this.errorHint();
            }
            NProgress.done();
        }).catch(function(err){
            console.error(err);
            this.errorHint();
        });
    }

    errorHint () {
        $(this.container).find("[role=alert]").hide();
        $(this.container).find("[data-error-hint]").show();
    }

    successHint () {
        $(this.container).find("[role=alert]").hide();
        $(this.container).find("[data-success-hint]").show();
    }

    render () {
        var html = clubInfoTmpl("club_info", this.data);
        $(this.container).html(html);
        $(this.container).find("[role=alert]").hide();
        this.initThirdComponenets();
        $(this.container).find("[data-club-type]").val(this.data.type);
        $(this.container).find("[data-club-locale]").val(this.data.locale);
        $(this.container).find("[data-club-show-type]").val(this.data.show_type);
        $(this.container).find("[data-club-is-apply]").prop("checked", this.data.is_allow_apply);
        $(this.container).find("[data-club-introduction]").val(this.data.introduction);
        $(this.container).find("[data-club-summary]").val(this.data.summary);
    }

    validateHonor (dom) {

        $(dom).find(".has-error").removeClass("has-error");
        $(dom).find(".glyphicon-remove").removeClass("glyphicon-remove");
        $(dom).find("[data-toggle=tooltip]").tooltip("destroy").attr("title", "");

        var $year = $(dom).find("[data-honor-year]");
        var $honor = $(dom).find("[data-honor-title]");

        var  validator = new Validator();
        
        validator.add($year, [{
            strategy: "isNonEmpty",
        }]);
        validator.add($honor, [{
            strategy: "isNonEmpty",
        },{
            strategy: "maxLength:15",
        }]);

        var result = validator.start();

        if(result && result.errorMsg){
            // show the tips and focus
            let $errorField = $(result.dom);
            $errorField.attr("title", result.errorMsg).tooltip("show");
            $errorField.closest(".form-group").removeClass("has-error").addClass("has-error");
            $errorField.siblings(".glyphicon").removeClass("glyphicon-remove").addClass("glyphicon-remove");
            $("body").scrollTop($errorField.offset().top);
            return false;
        }else{
            return true;
        }
    }

    validateClubImage (dom) {
        $(dom).find(".has-error").removeClass("has-error");
        $(dom).find(".glyphicon-remove").removeClass("glyphicon-remove");
        $(dom).find("[data-toggle=tooltip]").tooltip("destroy").attr("title", "");

        var $description = $(dom).find("[data-club-img-description]");
        var validator = new Validator();
        validator.add($description, [{
            strategy: "isNonEmpty"
        },{
            strategy: "maxLength:15"
        }]);
        
        var result = validator.start();
        if(result && result.errorMsg){
            // show the tips and focus
            let $errorField = $(result.dom);
            $errorField.attr("title", result.errorMsg).tooltip("show");
            $errorField.closest(".form-group").removeClass("has-error").addClass("has-error");
            $errorField.siblings(".glyphicon").removeClass("glyphicon-remove").addClass("glyphicon-remove");
            $("body").scrollTop($errorField.offset().top);
            return false;
        }else{
            return true;
        }
    }

    bindEvent(){
        var that = this;
        $(this.container).find("[data-action=submit-club-info]").unbind("click").bind("click", function(){
            
            $("#club-basic-info-form").find(".has-error").removeClass("has-error");
            $("#club-basic-info-form").find(".glyphicon-remove").removeClass("glyphicon-remove");
            $("#club-basic-info-form").find("[data-toggle=tooltip]").tooltip("destroy").attr("title", "");

            var validator = new Validator();

            var $form = $("#club-basic-info-form");
            var $type = $form.find("[data-club-type]");
            var $locale = $form.find("[data-club-locale]");
            var $email = $form.find("[data-club-email]");
            var $summary = $form.find("[data-club-summary]");
            var $introduction = $form.find("[data-club-introduction]");
            var $apply_url = $form.find("[data-club-apply-url]");
            var $url = $form.find("[data-club-url]");
            var $show_type = $form.find("[data-club-show-type]");
            var $is_apply = $form.find("[data-club-is-apply]");

            validator.add($email, [{
                strategy: "isNonEmpty",
                errorMsg: ""
            }, {
                strategy: "isEmail",
                errorMsg: ""
            }]);

            validator.add($summary, [{
                strategy: "isNonEmpty",
            },{
                strategy: "maxLength:80",
                errorMsg: ""
            }]);

            validator.add($introduction, [{
                strategy: "isNonEmpty",
                errorMsg: ""
            }]);

            if( $show_type.val() === "app" || $url.val() ){
                validator.add($url, [{
                    strategy: "isUrl",
                    errorMsg: ""
                }]);
            }

            if($is_apply.prop("checked")){
                validator.add($apply_url, [{
                    strategy: "isNonEmpty",
                    errorMsg: ""
                }, {
                    strategy: "isUrl",
                    errorMsg: ""
                }]);
            }

            var result = validator.start();
            if(result && result.errorMsg){
                // show the tips and focus
                let $errorField = $(result.dom);
                $errorField.attr("title", result.errorMsg).tooltip("show");
                $errorField.closest(".form-group").removeClass("has-error").addClass("has-error");
                $errorField.siblings(".glyphicon").removeClass("glyphicon-remove").addClass("glyphicon-remove");
                $("body").scrollTop($errorField.offset().top - 60);
            }else{
                // 成功验证
                waitMe.show();
                updateClubInfo({
                    club_id: that.club_id,
                    type: $type.val(),
                    locale: $locale.val(),
                    introduction: $introduction.val(),
                    summary: $summary.val(),
                    email: $email.val(),
                    apply_url: $apply_url.val(),
                    url: $url.val(),
                    is_allow_apply: $is_apply.prop("checked"),
                    show_type: $show_type.val() === "native" ? true : false
                }).then((res)=>{
                    $("body").scrollTop(0);
                    that.successHint();
                    waitMe.hide();
                }).catch((res)=>{
                    waitMe.hide();
                });
            }

        });
    }

    deconstructor (){
    }
}

export default ClubInfo;
